import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../base/imageres.dart';
import '../../base/constant.dart';
import '../../base/eventbus.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../native/nativechannel.dart';
import '../../views/jsw_base_view.dart';

///女性健康下面的经期设置
class MenstrualSettingPage extends StatefulWidget {
  final int cycleValue;
  final int periodValue;
  final int regularly;
  final int tracking;
  final int menstrualTime;

  const MenstrualSettingPage(
      {super.key,
      required this.menstrualTime,
      required this.cycleValue,
      required this.periodValue,
      required this.regularly,
      required this.tracking});

  @override
  State<StatefulWidget> createState() {
    return _MenstrualSettingPageState();
  }
}

class _MenstrualSettingPageState extends State<MenstrualSettingPage> {
  static const _tag =
      '[page_menstrual_setting.dart][_MenstrualSettingPageState]';

  StreamSubscription? _bus;

  ///生理周期的值
  var _cycleValue = 0;

  ///经期长度的值
  var _periodValue = 0;

  ///生理周期是否规律
  var _regularly = 0;

  ///女性健康目标值
  var _tracking = 0;

  @override
  void initState() {
    super.initState();
    _initEventBus();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    _cycleValue = widget.cycleValue > 0 ? widget.cycleValue : 0;
    _periodValue = widget.periodValue > 0 ? widget.periodValue : 0;
    _regularly = widget.regularly;
    _tracking = widget.tracking;
  }

  @override
  void dispose() {
    _cancelEventBus();
    super.dispose();
  }

  ///初始化EventBus
  void _initEventBus() {
    _bus = EventBusUtil.getInstance().on().listen((event) {
      switch (event.runtimeType) {
        case DataEvent:
          DataEvent dataEvent = event;
          switch (dataEvent.type) {
            case HealthDataType.REFRESH_SETTING_CYCLEVALUE:
              if (_cycleValue != dataEvent.data) {
                setState(() {
                  _cycleValue = dataEvent.data;
                });
                updateWomanHealthData();
              }
              break;
            case HealthDataType.REFRESH_SETTING_PERIODVALUE:
              if (_periodValue != dataEvent.data) {
                setState(() {
                  _periodValue = dataEvent.data;
                });
                updateWomanHealthData();
              }
              break;
            case HealthDataType.REFRESH_SETTING_REGULARLY:
              if (_regularly != dataEvent.data) {
                setState(() {
                  _regularly = dataEvent.data;
                });
                updateWomanHealthData();
              }
              break;
            case HealthDataType.REFRESH_SETTING_TARGETVALUE:
              if (_tracking != dataEvent.data) {
                setState(() {
                  _tracking = dataEvent.data;
                });
                updateWomanHealthData();
              }
              break;
          }
      }
    });
  }

  ///取消EventBus订阅
  void _cancelEventBus() {
    _bus?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(ImageRes.bg_health_set),
              fit: BoxFit.cover, // 图片填充方式
            ),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent, // 设置 Scaffold 背景透明
          appBar: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.transparent,
            title: EasyTouch(
              width: double.infinity,
              padding: const EdgeInsets.only(right: 55),
              child: Text(
                StringRes.menstrual_setting,
                textAlign: TextAlign.center,
                style: ThemeUtil.toolbar,
              ),
            ),
            leading: IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              hoverColor: Colors.transparent,
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                Get.back();
              },
            ),
          ),
          body: Column(
            children: [
              //平均生理周期天数
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  Get.toNamed(PageIndex.physiologicalCyclePage, arguments: {
                    "cycleValue": _cycleValue
                  });
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(top: 42, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 17, bottom: 17, left: 15, right: 15),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.physiological_cycle_content,
                          style: ThemeUtil.mp2,
                        ),
                        const Spacer(),
                        Container(
                            margin: const EdgeInsets.only(right: 8),
                            child: Text(
                              _cycleValue.toString(),
                              textAlign: TextAlign.center,
                              style: ThemeUtil.mp2.copyWith(
                                  color: const Color(
                                      ThemeUtil.primaryWhiteValue50)),
                            )),
                        const Image(
                          image: AssetImage(ImageRes.ic_arrow_right),
                          width: 8,
                          height: 10,
                          fit: BoxFit.cover,
                        ),
                      ],
                    )),
              ),

              //经期持续的时间
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  Get.toNamed(PageIndex.periodLengthPage, arguments: {
                    "isReset": true,
                    "cycleValue": _cycleValue,
                    "periodValue": _periodValue
                  });
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(top: 24, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 17, bottom: 17, left: 15, right: 15),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.period_length_content,
                          style: ThemeUtil.mp2,
                        ),
                        const Spacer(),
                        Container(
                            margin: const EdgeInsets.only(right: 8),
                            child: Text(
                              _periodValue.toString(),
                              textAlign: TextAlign.center,
                              style: ThemeUtil.mp2.copyWith(
                                  color: const Color(
                                      ThemeUtil.primaryWhiteValue50)),
                            )),
                        const Image(
                          image: AssetImage(ImageRes.ic_arrow_right),
                          width: 8,
                          height: 16,
                          fit: BoxFit.cover,
                        ),
                      ],
                    )),
              ),

              //生理周期规律情况
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  Get.toNamed(PageIndex.periodicLawPage, arguments: {
                    "isReset": true,
                    "regularly": _regularly,
                    "menstrualTime": widget.menstrualTime,
                    "cycleValue": _cycleValue,
                    "periodValue": _periodValue
                  });
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(top: 24, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 17, bottom: 17, left: 15, right: 15),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.periodic_law_content,
                          style: ThemeUtil.mp2,
                        ),
                        const Spacer(),
                        Container(
                            margin: const EdgeInsets.only(right: 8),
                            child: Text(
                              _regularly == 1
                                  ? StringRes.rule
                                  : StringRes.irregular,
                              textAlign: TextAlign.center,
                              style: ThemeUtil.mp2.copyWith(
                                  color: const Color(
                                      ThemeUtil.primaryWhiteValue50)),
                            )),
                        const Image(
                          image: AssetImage(ImageRes.ic_arrow_right),
                          width: 8,
                          height: 16,
                          fit: BoxFit.cover,
                        ),
                      ],
                    )),
              ),

              //目标
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  Get.toNamed(PageIndex.targetSettingPage,
                      arguments: _tracking);
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(top: 24, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 17, bottom: 17, left: 15, right: 15),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.target,
                          style: ThemeUtil.mp2,
                        ),
                        const Spacer(),
                        Container(
                            margin: const EdgeInsets.only(right: 8),
                            child: Text(
                              _tracking == 1
                                  ? StringRes.cycle_tracking_content
                                  : StringRes.conception_content,
                              textAlign: TextAlign.center,
                              style: ThemeUtil.mp2.copyWith(
                                  color: const Color(
                                      ThemeUtil.primaryWhiteValue50)),
                            )),
                        const Image(
                          image: AssetImage(ImageRes.ic_arrow_right),
                          width: 8,
                          height: 16,
                          fit: BoxFit.cover,
                        ),
                      ],
                    )),
              ),
            ],
          ),
        ),
      ],
    );
  }

  ///更新女性健康数据
  void updateWomanHealthData() {
    var timeString = DateFormat("yyyy-MM-dd").format(DateTime.fromMillisecondsSinceEpoch(widget.menstrualTime));
    Map<String, dynamic> dataMap = <String, dynamic>{};
    dataMap['health_menstrual_time'] = timeString;
    dataMap['health_cycle_value'] = _cycleValue;
    dataMap['health_period_length'] = _periodValue;
    dataMap['health_regularly'] = _regularly;
    dataMap['health_tracking'] = _tracking;
    Native.setWomenHealthData(dataMap);
  }
}
